package com.laundry.admin.ui.main

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.laundry.admin.R
import com.laundry.admin.databinding.ActivityMainBinding
import com.laundry.admin.ui.analytics.AnalyticsFragment
import com.laundry.admin.ui.dashboard.DashboardFragment
import com.laundry.admin.ui.keyword.KeywordFragment
import com.laundry.admin.ui.merchant.MerchantFragment
import com.laundry.admin.ui.monitoring.MonitoringFragment
import com.laundry.admin.ui.promotion.PromotionFragment
import com.laundry.admin.ui.user.UserFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityMainBinding
    private val viewModel: MainViewModel by viewModels()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        initViews()
        observeViewModel()
        
        // 默认显示仪表盘
        if (savedInstanceState == null) {
            showFragment(DashboardFragment(), "dashboard")
        }
    }
    
    private fun initViews() {
        setupBottomNavigation()
        setupToolbar()
        setupDrawer()
    }
    
    private fun setupBottomNavigation() {
        binding.bottomNavigation.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.nav_dashboard -> {
                    showFragment(DashboardFragment(), "dashboard")
                    binding.toolbarTitle.text = "管理中心"
                    true
                }
                R.id.nav_promotion -> {
                    showFragment(PromotionFragment(), "promotion")
                    binding.toolbarTitle.text = "投流管理"
                    true
                }
                R.id.nav_merchant -> {
                    showFragment(MerchantFragment(), "merchant")
                    binding.toolbarTitle.text = "商家管理"
                    true
                }
                R.id.nav_monitoring -> {
                    showFragment(MonitoringFragment(), "monitoring")
                    binding.toolbarTitle.text = "系统监控"
                    true
                }
                R.id.nav_analytics -> {
                    showFragment(AnalyticsFragment(), "analytics")
                    binding.toolbarTitle.text = "数据分析"
                    true
                }
                else -> false
            }
        }
    }
    
    private fun setupToolbar() {
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_menu)
        
        // 设置实时状态指示器
        binding.realTimeIndicator.setOnClickListener {
            showRealTimeStatus()
        }
    }
    
    private fun setupDrawer() {
        binding.drawerLayout?.let { drawerLayout ->
            binding.navigationView?.setNavigationItemSelectedListener { menuItem ->
                when (menuItem.itemId) {
                    R.id.nav_users -> {
                        showFragment(UserFragment(), "users")
                        binding.toolbarTitle.text = "用户管理"
                    }
                    R.id.nav_keywords -> {
                        showFragment(KeywordFragment(), "keywords")
                        binding.toolbarTitle.text = "关键词管理"
                    }
                    R.id.nav_settings -> {
                        navigateToSettings()
                    }
                    R.id.nav_logs -> {
                        navigateToLogs()
                    }
                    R.id.nav_backup -> {
                        showBackupDialog()
                    }
                    R.id.nav_logout -> {
                        showLogoutDialog()
                    }
                }
                drawerLayout.closeDrawers()
                true
            }
        }
    }
    
    private fun observeViewModel() {
        lifecycleScope.launch {
            viewModel.uiState.collect { state ->
                updateUI(state)
            }
        }
        
        lifecycleScope.launch {
            viewModel.events.collect { event ->
                handleEvent(event)
            }
        }
        
        lifecycleScope.launch {
            viewModel.systemAlerts.collect { alerts ->
                handleSystemAlerts(alerts)
            }
        }
    }
    
    private fun updateUI(state: MainUiState) {
        // 更新加载状态
        binding.progressBar.visibility = if (state.isLoading) View.VISIBLE else View.GONE
        
        // 更新网络状态
        if (!state.isNetworkAvailable) {
            showNetworkError()
        } else {
            hideNetworkError()
        }
        
        // 更新管理员信息
        state.adminProfile?.let { profile ->
            updateAdminProfile(profile)
        }
        
        // 更新系统状态
        updateSystemStatus(state.systemStatus)
        
        // 更新实时指标
        updateRealTimeMetrics(state.realTimeMetrics)
        
        // 更新告警数量
        updateAlertBadge(state.alertCount)
    }
    
    private fun handleEvent(event: MainEvent) {
        when (event) {
            is MainEvent.ShowError -> {
                showError(event.message)
            }
            is MainEvent.NavigateToLogin -> {
                navigateToLogin()
            }
            is MainEvent.ShowSystemAlert -> {
                showSystemAlert(event.alert)
            }
            is MainEvent.ShowCriticalError -> {
                showCriticalError(event.message)
            }
        }
    }
    
    private fun handleSystemAlerts(alerts: List<SystemAlert>) {
        if (alerts.isNotEmpty()) {
            val criticalAlerts = alerts.filter { it.level == "critical" }
            if (criticalAlerts.isNotEmpty()) {
                showCriticalAlertDialog(criticalAlerts)
            }
        }
    }
    
    private fun showFragment(fragment: Fragment, tag: String) {
        val currentFragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
        
        if (currentFragment?.tag == tag) {
            return
        }
        
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment, tag)
            .commit()
    }
    
    private fun updateAdminProfile(profile: com.laundry.admin.data.model.AdminProfile) {
        binding.navigationView?.getHeaderView(0)?.let { headerView ->
            headerView.findViewById<android.widget.TextView>(R.id.admin_name)?.text = profile.name
            headerView.findViewById<android.widget.TextView>(R.id.admin_role)?.text = profile.role
            
            // 加载管理员头像
            val avatarView = headerView.findViewById<android.widget.ImageView>(R.id.admin_avatar)
            com.laundry.admin.utils.ImageUtils.loadImage(
                avatarView,
                profile.avatar,
                R.drawable.ic_admin_placeholder
            )
        }
    }
    
    private fun updateSystemStatus(status: SystemStatus?) {
        status?.let {
            val statusColor = when (it.status) {
                "healthy" -> androidx.core.content.ContextCompat.getColor(this, R.color.green_500)
                "warning" -> androidx.core.content.ContextCompat.getColor(this, R.color.orange_500)
                "error" -> androidx.core.content.ContextCompat.getColor(this, R.color.red_500)
                else -> androidx.core.content.ContextCompat.getColor(this, R.color.gray_500)
            }
            
            binding.systemStatusIndicator.setBackgroundColor(statusColor)
            binding.systemStatusText.text = it.statusText
        }
    }
    
    private fun updateRealTimeMetrics(metrics: RealTimeMetrics?) {
        metrics?.let {
            binding.realTimeIndicator.visibility = View.VISIBLE
            
            // 更新实时数据显示
            binding.activeUsersCount.text = it.activeUsers.toString()
            binding.activeMerchantsCount.text = it.activeMerchants.toString()
            binding.ongoingOrdersCount.text = it.ongoingOrders.toString()
            binding.promotionSpendingText.text = "¥${String.format("%.2f", it.promotionSpending)}"
        }
    }
    
    private fun updateAlertBadge(count: Int) {
        if (count > 0) {
            binding.alertBadge.visibility = View.VISIBLE
            binding.alertBadge.text = if (count > 99) "99+" else count.toString()
        } else {
            binding.alertBadge.visibility = View.GONE
        }
    }
    
    private fun showRealTimeStatus() {
        val bottomSheet = com.laundry.admin.ui.common.RealTimeStatusBottomSheet()
        bottomSheet.show(supportFragmentManager, "real_time_status")
    }
    
    private fun showNetworkError() {
        binding.networkErrorView.visibility = View.VISIBLE
        binding.networkErrorView.setOnClickListener {
            viewModel.retry()
        }
    }
    
    private fun hideNetworkError() {
        binding.networkErrorView.visibility = View.GONE
    }
    
    private fun showError(message: String) {
        com.google.android.material.snackbar.Snackbar.make(
            binding.root,
            message,
            com.google.android.material.snackbar.Snackbar.LENGTH_LONG
        ).show()
    }
    
    private fun showSystemAlert(alert: SystemAlert) {
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("系统告警")
            .setMessage(alert.message)
            .setPositiveButton("查看详情") { _, _ ->
                navigateToAlertDetail(alert.id)
            }
            .setNegativeButton("忽略", null)
            .show()
    }
    
    private fun showCriticalError(message: String) {
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("严重错误")
            .setMessage(message)
            .setPositiveButton("立即处理") { _, _ ->
                binding.bottomNavigation.selectedItemId = R.id.nav_monitoring
            }
            .setCancelable(false)
            .show()
    }
    
    private fun showCriticalAlertDialog(alerts: List<SystemAlert>) {
        val alertMessages = alerts.joinToString("\n") { "• ${it.message}" }
        
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("紧急告警 (${alerts.size})")
            .setMessage(alertMessages)
            .setPositiveButton("立即处理") { _, _ ->
                binding.bottomNavigation.selectedItemId = R.id.nav_monitoring
            }
            .setNegativeButton("稍后处理", null)
            .show()
    }
    
    private fun showBackupDialog() {
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("数据备份")
            .setMessage("确定要开始数据备份吗？此操作可能需要几分钟时间。")
            .setPositiveButton("开始备份") { _, _ ->
                viewModel.startBackup()
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun showLogoutDialog() {
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("退出登录")
            .setMessage("确定要退出管理系统吗？")
            .setPositiveButton("退出") { _, _ ->
                viewModel.logout()
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                binding.drawerLayout?.openDrawer(androidx.core.view.GravityCompat.START)
                true
            }
            R.id.action_refresh -> {
                viewModel.refreshData()
                true
            }
            R.id.action_alerts -> {
                navigateToAlerts()
                true
            }
            R.id.action_export -> {
                showExportDialog()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    private fun navigateToSettings() {
        val intent = android.content.Intent(this, com.laundry.admin.ui.settings.SettingsActivity::class.java)
        startActivity(intent)
    }
    
    private fun navigateToLogs() {
        val intent = android.content.Intent(this, com.laundry.admin.ui.logs.LogsActivity::class.java)
        startActivity(intent)
    }
    
    private fun navigateToAlerts() {
        val intent = android.content.Intent(this, com.laundry.admin.ui.alert.AlertActivity::class.java)
        startActivity(intent)
    }
    
    private fun navigateToAlertDetail(alertId: String) {
        val intent = android.content.Intent(this, com.laundry.admin.ui.alert.AlertDetailActivity::class.java)
        intent.putExtra("alert_id", alertId)
        startActivity(intent)
    }
    
    private fun navigateToLogin() {
        val intent = android.content.Intent(this, com.laundry.admin.ui.auth.LoginActivity::class.java)
        startActivity(intent)
        finish()
    }
    
    private fun showExportDialog() {
        val bottomSheet = com.laundry.admin.ui.common.ExportBottomSheet()
        bottomSheet.show(supportFragmentManager, "export_dialog")
    }
    
    override fun onResume() {
        super.onResume()
        // 检查网络状态
        viewModel.checkNetworkStatus()
        
        // 刷新管理员信息
        if (viewModel.isLoggedIn()) {
            viewModel.refreshAdminProfile()
            viewModel.startRealTimeMonitoring()
        }
    }
    
    override fun onPause() {
        super.onPause()
        viewModel.stopRealTimeMonitoring()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        viewModel.cleanup()
    }
}

// UI状态数据类
data class MainUiState(
    val isLoading: Boolean = false,
    val isNetworkAvailable: Boolean = true,
    val adminProfile: com.laundry.admin.data.model.AdminProfile? = null,
    val systemStatus: SystemStatus? = null,
    val realTimeMetrics: RealTimeMetrics? = null,
    val alertCount: Int = 0,
    val error: String? = null
)

// 系统状态数据类
data class SystemStatus(
    val status: String, // healthy, warning, error
    val statusText: String,
    val uptime: Long,
    val version: String
)

// 实时指标数据类
data class RealTimeMetrics(
    val activeUsers: Int,
    val activeMerchants: Int,
    val ongoingOrders: Int,
    val promotionSpending: Double,
    val systemLoad: Double,
    val responseTime: Long
)

// 系统告警数据类
data class SystemAlert(
    val id: String,
    val level: String, // info, warning, error, critical
    val message: String,
    val timestamp: Long,
    val source: String
)

// 事件数据类
sealed class MainEvent {
    data class ShowError(val message: String) : MainEvent()
    object NavigateToLogin : MainEvent()
    data class ShowSystemAlert(val alert: SystemAlert) : MainEvent()
    data class ShowCriticalError(val message: String) : MainEvent()
}
